
//
//  PaymentChannelsViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/20.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "PaymentChannelsViewController.h"
#import "CloseAreaViewController.h"
#import "ExperienceModel.h"
#import "ExperViewController.h"
#import "SYPasswordView.h"

@interface PaymentChannelsViewController ()<UITextFieldDelegate,PayPassWordDelegate>
@property (nonatomic, strong)UITextField *nameField;
@property (nonatomic, strong)UITextField *moneyField;
@property (nonatomic, strong)UILabel *areaLab;
@property (nonatomic, strong)UILabel *exateceLab;
@property (nonatomic, strong)AddressModel *privesModel;
@property (nonatomic, strong)AddressModel *citysModel;
@property (nonatomic, strong)AddressModel *areasModel;
@property (nonatomic, strong)NSArray *experAry;
@property (nonatomic, strong)ExperienceModel *model;
@property (nonatomic, strong)SYPasswordView *pasView;
@property (nonatomic, strong)UIView *payPassView;
@property (nonatomic, strong)NSString *tradeNoStr;

@end

@implementation PaymentChannelsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _tradeNoStr = @"";
    [self creatUI];
    AddressModel *priModel = [[AddressModel alloc] init];
    priModel.ID = [LTools cacheForKey:SERVER_sheng];
    priModel.name = [LTools cacheForKey:SERVER_shengName];
    _privesModel = priModel;
    AddressModel *citModel = [[AddressModel alloc] init];
    citModel.ID = [LTools cacheForKey:SERVER_shi];
    citModel.name = [LTools cacheForKey:SERVER_shiName];
    _citysModel = citModel;
    AddressModel *areModel = [[AddressModel alloc] init];
    areModel.ID = [LTools cacheForKey:SERVER_qu];
    areModel.name = [LTools cacheForKey:SERVER_quName];
    _areasModel = areModel;
    NSDictionary *dic = @{@"cityId": [LTools cacheForKey:SERVER_shi],
                            @"provinceId": [LTools cacheForKey:SERVER_sheng],
                            @"districtId":[LTools cacheForKey:SERVER_qu]
                            };
    [self requestExperienceShop:dic];
}

- (void)creatUI
{
    self.navigationItem.title = @"支付通道";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = BacksColor;
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180*displaywidth)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    NSArray *titAry = @[@"地区",@"体验馆",@"项目名称",@"金额"];
    NSArray *pladerAry = @[@"",@"",@"请输入项目名称",@"请输入金额"];
    for (int i = 0; i < titAry.count; i++)
    {
        UILabel *titleLabel = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 45*displaywidth*i+5*displaywidth , 80*displaywidth, 35*displaywidth) Font:14.0 Text:titAry[i] Color:RGB(77, 77, 77)];
        [whiteView addSubview:titleLabel];
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 45*displaywidth*i-1*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineView.backgroundColor = LinesColor;
        [whiteView addSubview:lineView];
        if (i < 2)
        {
            UILabel *addressLab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 45*displaywidth*i+5*displaywidth, SCREEN_WIDTH-140*displaywidth, 35*displaywidth) Font:15.0 Text:@"" Color:RGB(77, 77, 77)];
            addressLab.textAlignment = NSTextAlignmentRight;
            [whiteView addSubview:addressLab];
            if (i == 0)
            {
                addressLab.text = [NSString stringWithFormat:@"%@-%@-%@",[LTools cacheForKey:SERVER_shengName],[LTools cacheForKey:SERVER_shiName],[LTools cacheForKey:SERVER_quName]];
                _areaLab = addressLab;
            }
            else
            {
                _exateceLab = addressLab;
            }
            UIImageView *imgview = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-35*displaywidth, 45*displaywidth*i+15*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"nextimg"];
            imgview.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:imgview];
            UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(150*displaywidth, 45*displaywidth*i, SCREEN_WIDTH, 45*displaywidth) ImageName:nil Target:self Action:@selector(closeTypeAction:) Title:nil Font:12.0];
            btn.backgroundColor = [UIColor clearColor];
            btn.tag = 100 + i;
            [whiteView addSubview:btn];
            
        }
        else
        {
            UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(100*displaywidth, 45*displaywidth*i+5*displaywidth, SCREEN_WIDTH-120*displaywidth, 35*displaywidth) placeholder:pladerAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
            [textfield setValue:RGB(179, 179, 179) forKeyPath:@"_placeholderLabel.textColor"];
            textfield.textColor = RGB(77, 77, 77);
            textfield.textAlignment = NSTextAlignmentRight;
            textfield.delegate = self;
            [whiteView addSubview:textfield];
            if (i == 2)
            {
                _nameField = textfield;
            }
            else
            {
                textfield.keyboardType = UIKeyboardTypeDecimalPad;
                _moneyField = textfield;
            }
        }
       
    }
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , 220*displaywidth, SCREEN_WIDTH-120*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureAction) Title:@"确认" Font:15.0];
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.backgroundColor = ThemeColor;
    [soureBtn.layer setMasksToBounds:YES];
    [soureBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:soureBtn];
}

- (void)closeTypeAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    if (btn.tag == 100)
    {
        CloseAreaViewController *vc = [[CloseAreaViewController alloc] init];
        WEAKSELF;
        vc.chooseblock = ^(AddressModel *priveModel, AddressModel *cityModel, AddressModel *areaModel)
        {
            weakSelf.privesModel = priveModel;
            weakSelf.citysModel = cityModel;
            weakSelf.areasModel = areaModel;
            NSDictionary *dic = @{@"cityId": s_str(cityModel.ID),
                                  @"provinceId": s_str(priveModel.ID),
                                  @"districtId":s_str(areaModel.ID)};
            [weakSelf requestExperienceShop:dic];
            dispatch_async(dispatch_get_main_queue(), ^{
                _areaLab.text = [NSString stringWithFormat:@"%@-%@-%@",priveModel.name,cityModel.name,areaModel.name];
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        ExperViewController *vc = [[ExperViewController alloc] init];
        vc.experArray = _experAry;
        WEAKSELF;
        vc.closeBlock = ^(ExperienceModel *model)
        {
            weakSelf.model = model;
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.exateceLab.text = model.nickname;
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

- (void)soureAction
{
    if (!_model)
    {
        [LTools showMBProgressWithText:@"请选择体验馆" addToView:self.view];
        return;
    }
    if ([_nameField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入项目名称" addToView:self.view];
        return;
    }
    if ([_moneyField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入金额" addToView:self.view];
        return;
    }
    WEAKSELF;
    NSDictionary *dic = @{@"cityId":s_str(_citysModel.ID),
                          @"cityText":_citysModel.name,
                          @"clientId":@"4",
                          @"districtId":s_str(_areasModel.ID),
                          @"districtText":_areasModel.name,
                          @"experienceShopId":s_str(_model.ID),
                          @"payMoney":_moneyField.text,
                          @"projectName":_nameField.text,
                          @"provinceId":s_str(_privesModel.ID),
                          @"provinceText":_privesModel.name};
    [HYBaseHandler requestPaymentChannelParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            NSString *tradeStr = obj[@"data"][@"tradeNo"];
            weakSelf.tradeNoStr = tradeStr;
            [weakSelf creatPayPassWordView];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
    
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)requestExperienceShop:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestExperienceShopParmers:dic Success:^(id obj)
    {
        if ([obj server_Getcodecheck])
        {
            weakSelf.experAry = [ExperienceModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.experAry.count > 0)
                {
                    weakSelf.model = weakSelf.experAry[0];
                    weakSelf.exateceLab.text = weakSelf.model.nickname;
                }
                else
                {
                    weakSelf.model = nil;
                    weakSelf.exateceLab.text = @"";
                }
                
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        
    } failed:^(NSError *error) {
        
    }];
}


- (void)creatPayPassWordView
{
    if (!self.payPassView)
    {
        self.payPassView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _payPassView.backgroundColor = RGBA(0, 0, 0, 0.5);
        [sharedDelegate.window addSubview:_payPassView];
        UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 230*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-230*displaywidth)];
        secondView.backgroundColor = RGB(242, 242, 242);
        [_payPassView addSubview:secondView];
        UILabel *titleLabel = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2-80*displaywidth, 0, 160*displaywidth, 44*displaywidth) Font:15.0 Text:@"请输入密码" Color:RGB(77, 77, 77)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [secondView addSubview:titleLabel];
        UIButton *contactBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-60*displaywidth, 0, 44*displaywidth, 44*displaywidth) ImageName:@"chacha" Target:self Action:@selector(contactAction) Title:nil Font:13.0];
        contactBtn.backgroundColor = [UIColor clearColor];
        [secondView addSubview:contactBtn];
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 44*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineview.backgroundColor = RGB(210, 210, 210);
        [secondView addSubview:lineview];
        //        UILabel *moneyLabel = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 55*displaywidth, SCREEN_WIDTH-30*displaywidth, 25*displaywidth) Font:15.0 Text:@"充值金额 2000" Color:RGB(77, 77, 77)];
        //        moneyLabel.textAlignment = NSTextAlignmentCenter;
        //        [secondView addSubview:moneyLabel];
        self.pasView = [[SYPasswordView alloc] initWithFrame:CGRectMake(15*displaywidth, 90*displaywidth, SCREEN_WIDTH-30*displaywidth, 44*displaywidth)];
        _pasView.delegate = self;
        [secondView addSubview:_pasView];
        UIButton *forgotBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-115*displaywidth, 150*displaywidth, 100*displaywidth, 20*displaywidth) ImageName:nil Target:self Action:@selector(FindPassword) Title:@"忘记密码" Font:13.0];
        [forgotBtn setTitleColor:RGB(255, 111, 28) forState:UIControlStateNormal];
        [secondView addSubview:forgotBtn];
    }
    _payPassView.hidden = NO;
    [_pasView.textField becomeFirstResponder];
}
- (void)shuruSuccessValue:(NSString *)value
{
    [self requestPublicKey:value];
    NSLog(@"密码-----%@",value);
}
- (void)requestPublicKey:(NSString *)passWorld
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];
    [HYBaseHandler requestPublicKeyParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             NSString *publicKey = obj[@"data"];
             //测试要加密的数据
             NSString *sourceStr = passWorld;
             //公钥加密
             NSString *encryptStr = [RSA encryptString:sourceStr publicKey:publicKey];
             [weakSelf requestWalletPay:encryptStr];
             
         }
         else
         {
             [self.pasView clearUpPassword];
             [LTools showMBProgressWithText:obj[@"msg"] addToView:sharedDelegate.window];
             [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
     }];
}

- (void)requestWalletPay:(NSString *)pass
{
    WEAKSELF;
    NSDictionary *dic = @{@"tradeNo":_tradeNoStr,
                          @"password":pass
                          };
    [HYBaseHandler requestWalletPayParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         if ([obj server_Getcodecheck])
         {
             [LTools showMBProgressWithText:@"支付成功" addToView:sharedDelegate.window];
             weakSelf.payPassView.hidden = YES;
             [weakSelf.pasView endEditing:YES];
             [weakSelf.pasView clearUpPassword];
             [weakSelf.payPassView removeFromSuperview];
             [weakSelf.navigationController popToRootViewControllerAnimated:YES];
         }
         else
         {
             [self.pasView clearUpPassword];
             [LTools showMBProgressWithText:obj[@"msg"] addToView:sharedDelegate.window];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         
     }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
